package evolution.individual;

import evolution.problem.OptimizationProblem;
import evolution.problem.ProblemConstraints;
import evolution.random.RandomGenerator;

public class RandomIndividualFactory implements IndividualsFactory {

	private OptimizationProblem optimizationProblem;
	private RandomGenerator randomGenerator;

	public RandomIndividualFactory(OptimizationProblem optimizationProblem,
			RandomGenerator randomGenerator) {
		this.optimizationProblem = optimizationProblem;
		this.randomGenerator = randomGenerator;
	}

	@Override
	public Individual create() {
		RealCodedIndividual realCodedIndividual = new RealCodedIndividual();
		realCodedIndividual.setFitnessFunction(optimizationProblem
				.getFitnessFunction());

		double[] chromosome = generateChromosome();
		realCodedIndividual.setChromosome(chromosome);

		return realCodedIndividual;
	}

	public double[] generateChromosome() {
		ProblemConstraints constraints = optimizationProblem.getConstraints();
		int dimensions = constraints.getDimensions();
		double[] chromosome = new double[dimensions];

		for (int i = 0; i < dimensions; i++) {
			double random = randomGenerator.nextDouble();
			double minArg = constraints.getMinArg();
			double range = Math.abs(constraints.getMaxArg() - minArg);
			double val = random * range + minArg;
			chromosome[i] = val;
		}

		return chromosome;
	}
}
